package org.example.netDemo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.Iterator;

/**
 * Java 网络Nio编程 Http服务器，线程池演示
 */
public class HttpServer {
    private static int port=8080;
    public static void main(String[] args) throws Exception {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress((port)));
        serverSocketChannel.configureBlocking(false);

        // 选择器，处理多个请求
        Selector selector = Selector.open();

        // 管理选择器
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        System.out.println("服务器启动，运行端口:"+port);
        while (true) {
            if (selector.select(3000) == 0) {
                continue;
            }

            // 循环迭代处理每一个请求
            Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();

            while (keyIter.hasNext()) {
                SelectionKey key = keyIter.next();
                // 开启一个处理http响应的线程
                new Thread(new HttpHandler(key)).run();
                keyIter.remove();
            }
        }
    }

    static class HttpHandler implements Runnable {
        // 缓冲区
        private int bufferSize = 1024;
        private String localCharset = "UTF-8";
        private SelectionKey key;

        public HttpHandler(SelectionKey key) {
            this.key = key;
        }

        public void handleAccept() throws IOException {
            SocketChannel clientChannel =
                    ((ServerSocketChannel) key.channel()).accept();
            // 设置为非阻塞模式
            clientChannel.configureBlocking(false);
            clientChannel.register(
                    key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(bufferSize)
            );
        }

        // 接收到数据处理
        public void handleRead() throws IOException {
            // SocketChannel 可以认为是一个TCP Stream
            SocketChannel sc = (SocketChannel) key.channel();
            ByteBuffer buffer = (ByteBuffer) key.attachment();
            buffer.clear();

            if (sc.read(buffer) == -1) {
                sc.close();
            } else {
                buffer.flip();
                // 从缓冲区解码数据为字符串
                String receiveString = Charset.forName(localCharset).newDecoder().decode(buffer).toString();

                String[] requestMessage = receiveString.split("\r\n");
                for (String s : requestMessage) {
                    System.out.println(s);
                    if (s.isEmpty()) {
                        break;
                    }
                }

                String[] firstLine = requestMessage[0].split(" ");
                // 打印接收到的数据,http头内容
                System.out.println();
                System.out.println("Method:\t" + firstLine[0]);
                System.out.println("url:\t" + firstLine[1]);
                System.out.println("HTTP Version:\t" + firstLine[2]);
                System.out.println();

                // 拼接返回给浏览器的内容
                StringBuilder sendString = new StringBuilder();
                sendString.append("HTTP/1.1 200 OK\r\n");
                sendString.append("Content-Type:text/html;Charset=" + localCharset + "\r\n");
                sendString.append("\r\n");
                // http body 内容
                sendString.append("<html><head><title>SHOW</title></head></body>");


                sendString.append("这是一个网页<br/>");
                sendString.append(new Date().toString() + "<br/>");
                sendString.append("</body></html>");
                buffer = ByteBuffer.wrap(sendString.toString().getBytes(localCharset));
                // 向通道中写入数据
                sc.write(buffer);
                sc.close();
            }
        }

        // 线程启动入口方法
        @Override
        public void run() {
            try {
                if (key.isAcceptable()) {
                    handleAccept();
                }
                if (key.isReadable()) {
                    handleRead();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

